/*
 * Copyright 1999,2004 The Apache Software Foundation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.googlecode.webduff.methods;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.googlecode.webduff.WebdavStatus;
import com.googlecode.webduff.exceptions.AccessDeniedException;
import com.googlecode.webduff.exceptions.MethodResponseError;
import com.googlecode.webduff.exceptions.ObjectAlreadyExistsException;
import com.googlecode.webduff.exceptions.ObjectNotFoundException;
import com.googlecode.webduff.exceptions.WebdavException;
import com.googlecode.webduff.io.URI;
import com.googlecode.webduff.locking.AcquiredLock;
import com.googlecode.webduff.locking.LockFailedException;
import com.googlecode.webduff.locking.ResourceLocks;
import com.googlecode.webduff.util.RequestUtil;

import java.io.IOException;
import java.util.Hashtable;

public class DoCopy extends ReportingMethod {

	@SuppressWarnings("unused")
	private static org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(DoCopy.class);

    private DoDelete doDeleteMethod;
    
    public MethodResponse execute(HttpServletRequest req, HttpServletResponse resp) throws IOException, MethodResponseError {
        doDeleteMethod = (DoDelete) getMethod("DELETE");
        
        URI theURI = getURIForRequest(req);
        MethodResponse theResponse = new MethodResponse(resp);
        AcquiredLock acquiredLock = null;
        
        try {
			acquiredLock = acquireSharedLock(theURI, ResourceLocks.INFINITE, req);
		} catch (LockFailedException e) {
			throw new MethodResponseError(WebdavStatus.SC_LOCKED);
		}
        
		try {
            copyResource(req, theResponse);
        } catch (AccessDeniedException e) {
            throw new MethodResponseError(WebdavStatus.SC_FORBIDDEN);
        } catch (ObjectAlreadyExistsException e) {
        	throw new MethodResponseError(WebdavStatus.SC_CONFLICT, req.getRequestURI());
        } catch (ObjectNotFoundException e) {
        	throw new MethodResponseError(WebdavStatus.SC_NOT_FOUND, req.getRequestURI());
        } catch (WebdavException e) {
        	throw new MethodResponseError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
        } finally {
            acquiredLock.unlock();
        }
        
        return theResponse;
    }

    /**
     * Copy a resource.
     *
     * @param req
     *            Servlet request
     * @param response TODO
     * @return true if the copy is successful
     * @throws WebdavException
     *             if an error in the underlying store occurs
     * @throws IOException
     *             when an error occurs while sending the response
     * @throws MethodResponseError 
     */
    public boolean copyResource(HttpServletRequest req, MethodResponse response) throws WebdavException, IOException, MethodResponseError {
        // Parsing destination header
        String destinationPath = req.getHeader("Destination");

        if (destinationPath == null) {
            throw new MethodResponseError(WebdavStatus.SC_BAD_REQUEST);
        }

        // Remove url encoding from destination
        destinationPath = RequestUtil.URLDecode(destinationPath, "UTF8");

        int protocolIndex = destinationPath.indexOf("://");
        if (protocolIndex >= 0) {
            // if the Destination URL contains the protocol, we can safely
            // trim everything upto the first "/" character after "://"
            int firstSeparator = destinationPath.indexOf("/", protocolIndex + 4);
            if (firstSeparator < 0) {
                destinationPath = "/";
            } else {
                destinationPath = destinationPath.substring(firstSeparator);
            }
        } else {
            String hostName = req.getServerName();
            if ((hostName != null) && (destinationPath.startsWith(hostName))) {
                destinationPath = destinationPath.substring(hostName.length());
            }

            int portIndex = destinationPath.indexOf(":");
            if (portIndex >= 0) {
                destinationPath = destinationPath.substring(portIndex);
            }

            if (destinationPath.startsWith(":")) {
                int firstSeparator = destinationPath.indexOf("/");
                if (firstSeparator < 0) {
                    destinationPath = "/";
                } else {
                    destinationPath = destinationPath.substring(firstSeparator);
                }
            }
        }
        
        // Normalise destination path (remove '.' and '..')
        destinationPath = normalize(destinationPath);

        String contextPath = req.getContextPath();
        if ((contextPath != null) && (destinationPath.startsWith(contextPath))) {
            destinationPath = destinationPath.substring(contextPath.length());
        }

        String pathInfo = req.getPathInfo();
        if (pathInfo != null) {
            String servletPath = req.getServletPath();
            if ((servletPath != null) && (destinationPath.startsWith(servletPath))) {
                destinationPath = destinationPath.substring(servletPath.length());
            }
        }

        URI destinationURI = new URI(destinationPath);
        URI theURI = new URI(getRelativePath(req));

        // if source = destination
        if (theURI.equals(destinationPath)) {
            throw new MethodResponseError(HttpServletResponse.SC_FORBIDDEN);
        }

        // Parsing overwrite header

        boolean overwrite = true;
        String overwriteHeader = req.getHeader("Overwrite");

        if (overwriteHeader != null) {
            overwrite = overwriteHeader.equalsIgnoreCase("T");
        }
        
        AcquiredLock acquiredLock = null;
        
        try {
			acquiredLock = acquireSharedLock(theURI, ResourceLocks.INFINITE, req);
		} catch (LockFailedException e) {
			throw new MethodResponseError(WebdavStatus.SC_LOCKED);
		}
        
        try {
            // Retrieve the resources
            if (!store.objectExists(theURI)) {
                throw new MethodResponseError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            }

            boolean exists = store.objectExists(destinationURI);
            Hashtable<String, Integer> errorList = new Hashtable<String, Integer>();

            if (overwrite) {
                // Delete destination resource, if it exists
                if (exists) {
                    doDeleteMethod.deleteResource(destinationURI, errorList, response, req);
                } else {
                    response.setStatusCode(WebdavStatus.SC_CREATED);
                }
            } else {
                // If the destination exists, then it's a conflict
                if (exists) {
                    throw new MethodResponseError(WebdavStatus.SC_PRECONDITION_FAILED);
                } else {
                    response.setStatusCode(WebdavStatus.SC_CREATED);
                }
            }
            copy(theURI, destinationURI, errorList, req);
            if (!errorList.isEmpty()) {
                sendReport(req, errorList, response);
            }
        } finally {
            acquiredLock.unlock();
        }
        return true;
    }

    /**
     * copies the specified resource(s) to the specified destination.
     * preconditions must be handled by the caller. Standard status codes must
     * be handled by the caller. a multi status report in case of errors is
     * created here.
     *
     * @param sourceURI
     *            path from where to read
     * @param destinationURI
     *            path where to write
     * @param req
     *            HttpServletRequest
     * @throws WebdavException
     *             if an error in the underlying store occurs
     * @throws IOException
     * @throws MethodResponseError 
     */
    private void copy(URI sourceURI, URI destinationURI,
            Hashtable<String, Integer> errorList, HttpServletRequest req) throws WebdavException, IOException, MethodResponseError {

        if (store.isResource(sourceURI)) {
            store.createResource(destinationURI);
            store.setResourceContent(destinationURI, store.getResourceContent(sourceURI), null, null);
        } else {

            if (store.isFolder(sourceURI)) {
                copyFolder(sourceURI, destinationURI, errorList, req);
            } else {
                throw new MethodResponseError(WebdavStatus.SC_NOT_FOUND);
            }
        }
    }

    /**
     * helper method of copy() recursively copies the FOLDER at source path to
     * destination path
     *
     * @param sourceURI
     *            where to read
     * @param destinationURI
     *            where to write
     * @param errorList
     *            all errors that ocurred
     * @param req
     *            HttpServletRequest
     * @throws WebdavException
     *             if an error in the underlying store occurs
     */
    private void copyFolder(URI sourceURI, URI destinationURI,
            Hashtable<String, Integer> errorList, HttpServletRequest req) throws WebdavException {

        store.createFolder(destinationURI);
        boolean infiniteDepth = true;
        if (req.getHeader("depth") != null) {
            if (req.getHeader("depth").equals("0")) {
                infiniteDepth = false;
            }
        }
        if (infiniteDepth) {
            String[] children = store.getChildrenNames(sourceURI);

            for (int i = children.length - 1; i >= 0; i--) {
                children[i] = "/" + children[i];
                try {
                    if (store.isResource(sourceURI.append(children[i]))) {
                        store.createResource(destinationURI.append(children[i]));
                        store.setResourceContent(destinationURI.append(children[i]), store.getResourceContent(sourceURI.append(children[i])), null, null);
                    } else {
                        copyFolder(sourceURI.append(children[i]), destinationURI.append(children[i]), errorList, req);
                    }
                } catch (AccessDeniedException e) {
                    errorList.put(destinationURI.append(children[i]).getPath(), new Integer(WebdavStatus.SC_FORBIDDEN));
                } catch (ObjectNotFoundException e) {
                    errorList.put(destinationURI.append(children[i]).getPath(), new Integer(WebdavStatus.SC_NOT_FOUND));
                } catch (ObjectAlreadyExistsException e) {
                    errorList.put(destinationURI.append(children[i]).getPath(), new Integer(WebdavStatus.SC_CONFLICT));
                } catch (WebdavException e) {
                    errorList.put(destinationURI.append(children[i]).getPath(), new Integer(WebdavStatus.SC_INTERNAL_SERVER_ERROR));
                }
            }
        }
    }

    /**
     * Return a context-relative path, beginning with a "/", that represents the
     * canonical version of the specified path after ".." and "." elements are
     * resolved out. If the specified path attempts to go outside the boundaries
     * of the current context (i.e. too many ".." path elements are present),
     * return <code>null</code> instead.
     *
     * @param path
     *            Path to be normalized
     */
    protected String normalize(String path) {
        if (path == null)
            return null;

        // Create a place for the normalized path
        String normalized = path;

        if (normalized.equals("/."))
            return "/";

        // Normalize the slashes and add leading slash if necessary
        if (normalized.indexOf('\\') >= 0)
            normalized = normalized.replace('\\', '/');
        if (!normalized.startsWith("/"))
            normalized = "/" + normalized;

        // Resolve occurrences of "//" in the normalized path
        while (true) {
            int index = normalized.indexOf("//");
            if (index < 0)
                break;
            normalized = normalized.substring(0, index)
                    + normalized.substring(index + 1);
        }

        // Resolve occurrences of "/./" in the normalized path
        while (true) {
            int index = normalized.indexOf("/./");
            if (index < 0)
                break;
            normalized = normalized.substring(0, index)
                    + normalized.substring(index + 2);
        }

        // Resolve occurrences of "/../" in the normalized path
        while (true) {
            int index = normalized.indexOf("/../");
            if (index < 0)
                break;
            if (index == 0)
                return (null); // Trying to go outside our context
            int index2 = normalized.lastIndexOf('/', index - 1);
            normalized = normalized.substring(0, index2)
                    + normalized.substring(index + 3);
        }

        // Return the normalized path that we have completed
        return (normalized);
    }

}